<template>
  <a-card>
    <a-spin :spinning="spinning" size="large">
      <a-form @submit="handleSubmit" :form="form" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
        <a-form-item label="商品类型" has-feedback>
          <a-select
            v-decorator="['goodsType', { rules: [{ required: true, message: '请选择商品类型！' }], initialValue: '2000' }]"
            placeholder="请选择"
            :getPopupContainer="triggerNode => triggerNode.parentNode"
          >
            <a-select-option value="2000">
              会员卡
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="会员卡名" has-feedback>
          <a-input
            v-decorator="[
              'name',
              {
                rules: [
                  {
                    required: true,
                    max: 15,
                    message: '请输入会员卡名，不超过15个字符,不可输入符号！',
                    whitespace: true,
                    pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/
                  }
                ]
              }
            ]"
            name="name"
            placeholder="请输入"
            :max-length="15"
            autocomplete="off"
          />
        </a-form-item>
        <a-form-item label="会员卡类型" has-feedback>
          <a-select v-decorator="['memberType', { rules: [{ required: true, message: '请选择会员卡类型!' }] }]" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
            <a-select-option value="1">
              订阅卡
            </a-select-option>
            <a-select-option value="2">
              体验卡
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="描述" has-feedback>
          <a-input v-decorator="['label', { rules: [{ required: true, max: 8, message: '请输入描述，不超过8个字符！' }] }]" name="name" placeholder="请输入" :max-length="8" autocomplete="off" />
        </a-form-item>
        <a-form-item label="介绍" has-feedback>
          <a-textarea rows="4" placeholder="请输入" :max-length="100" v-decorator="['content', { rules: [{ required: true, max: 100, message: '请输入介绍，不超过100个字符！' }] }]" />
        </a-form-item>
        <a-form-item label="价格(元)" has-feedback>
          <a-input
            v-decorator="['price', { rules: [{ required: true, pattern: /^([0-9][0-9]*)+(\.[0-9]{1,2})?$/, message: '请输入价格,小数点后保留两位！', whitespace: true }] }]"
            name="name"
            placeholder="请输入"
            autocomplete="off"
          />
        </a-form-item>
        <a-form-item label="有效期(天)" has-feedback>
          <a-input
            v-decorator="['days', { rules: [{ required: true, pattern: /^[1-9]\d*$/, message: '请输入有效期，且是正整数！', whitespace: true }] }]"
            name="name"
            placeholder=" 请输入"
            autocomplete="off"
          />
        </a-form-item>
        <a-form-item label="图标">
          <a-upload
            v-decorator="['upload', { rules: [{ required: true, message: '请上传图标！' }] }]"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="https://up-z0.qiniup.com/"
            :before-upload="beforeUpload"
            :data="formBasePicData"
            :headers="headers"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="icon-img" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                Upload
              </div>
            </div>
            <a-input v-decorator="['posterImg']" type="hidden" />
          </a-upload>
        </a-form-item>
        <a-divider />
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary">提交</a-button>
          <a-button style="margin-left: 18px" @click="handleBack">取消</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>
<script>
import { uploadToken } from '@/api/api'
import { goodsCreate, goodsDetail } from '@/api/box/product'
import { uploadImgHost } from '@/assets/js/common'

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}

export default {
  data() {
    return {
      spinning: true,
      form: this.$form.createForm(this),
      loading: false,
      imageUrl: '',
      formBasePicData: {
        token: '',
        key: ''
      },
      headers: {
        authorization: 'authorization-text'
      },
      uploadToken: '',
      imgBaseUrl: '',
      productId: null,
      memberCardId: null,
      memberCardTypeId: null,
      skuId: null
    }
  },
  created() {
    this.imgBaseUrl = uploadImgHost
  },
  activated() {
    this.fetchPathId()
  },
  mounted() {},
  activated() {
    this.fetchPathId()
  },
  methods: {
    fetchPathId() {
      // console.log(this.$route.params.id)
      this.fetchUploadToken()
      const id = this.$route.params.id
      this.productId = this.$route.params.id
      if (id !== 'add') {
        this.fetchData(id)
      } else {
        this.form.getFieldsValue()
        this.form.setFieldsValue({
          goodsType: '2000',
          name: '',
          memberType: '',
          label: '',
          content: '',
          price: '',
          days: '',
          posterImg: '',
          upload: ''
        })
        this.imageUrl = ''
        this.spinning = false
      }
    },
    fetchData(id) {
      const data = {
        requestData: id
      }
      goodsDetail(data)
        .then(res => {
          console.log(res)
          if (res.code === 0) {
            const data = res.data
            data.price = data.price / 100
            data.goodsType = data.goodsType + ''
            data.memberType = data.memberType + ''
            this.form.getFieldsValue()
            this.form.setFieldsValue({
              goodsType: data.goodsType,
              name: data.name,
              memberType: data.memberType,
              label: data.label,
              content: data.content,
              price: data.price,
              days: data.days,
              posterImg: data.posterImg,
              upload: data.posterImg
            })
            this.memberCardId = data.memberCardId
            this.memberCardTypeId = data.memberCardTypeId
            this.skuId = data.skuId
            this.imageUrl = data.posterImg
            // console.log(this.imageUrl)
            this.spinning = false
          } else {
            this.spinning = false
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('fetchData:' + err)
        })
    },
    fetchUploadToken() {
      uploadToken()
        .then(res => {
          if (res.code === 0) {
            this.uploadToken = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('fetchUploadToken:' + err)
        })
    },
    handleChange(info) {
      // console.log(info)
      // const fileList = info.fileList
      // console.log(fileList)
      getBase64(info.file.originFileObj, imageUrl => {
        this.imageUrl = imageUrl
      })
      if (info.file.status === 'done') {
        const imgUrl = info.fileList[info.fileList.length - 1]
        this.form.setFieldsValue({
          posterImg: this.imgBaseUrl + imgUrl.response.key
        })
      }
      // fileList = fileList.map(file => {
      //   if (file.response) {
      //     file.url = this.imgBaseUrl + file.response.key
      //     console.log('上传成功', file.response)
      //   }
      //   return file
      // })
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      if (isLt2M && isJpgOrPng) {
        const key = new Date().getTime() + '-' + file.name
        this.formBasePicData.key = key
        this.formBasePicData.token = this.uploadToken
        return isJpgOrPng && isLt2M
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        // console.log(err)
        if (!err) {
          // console.log('Received values of form: ', values)
          const data = values
          delete data.upload
          const price = data.price
          data.price = parseInt(price * 100)
          console.log(data)
          this.submitCreate(data)
        }
      })
    },
    submitCreate(d) {
      const data = {
        requestData: d
      }
      if (this.productId !== 'add') {
        data.requestData.id = this.productId
        data.requestData.memberCardId = this.memberCardId
        data.requestData.memberCardTypeId = this.memberCardTypeId
        data.requestData.skuId = this.skuId
      }
      console.log(data)
      goodsCreate(data)
        .then(res => {
          console.log(res)
          if (res.code === 0) {
            this.$message.success(res.msg)
            this.$router.push('/box/product/fictitious/list')
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('submitCreate:' + err)
        })
    },
    handleBack() {
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped>
.icon-img {
  width: 86px;
  height: 86px;
  object-fit: scale-down;
}
</style>
